package org.acghub.mtdb.core;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

final class TBeanReflections {

    final static Map<Class<? extends TBean>, Map<String, Field>> INFOS = new ConcurrentHashMap<>();

    static Map<String, Field> getFieldsMap(TBean xbean) {
        Class<? extends TBean> clazz = xbean.getClass();
        return INFOS.computeIfAbsent(clazz, v -> {
            Map<String, Field> map = new HashMap<>();
            Field[] fields = clazz.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);
            for (Field field : fields) {
                map.put(field.getName(), field);
            }
            return map;
        });
    }

    static Object getValue(TBean xbean, String varname) {
        try {
            return getFieldsMap(xbean).get(varname).get(xbean);
        } catch (Exception e) {
            return null;
        }
    }

    static void setValue(TBean xbean, String varname, Object value) {
        try {
            getFieldsMap(xbean).get(varname).set(xbean, value);
        } catch (Exception ignored) {
        }
    }

    static Collection<Field> getFields(TBean xbean) {
        return getFieldsMap(xbean).values();
    }
}
